/*
Copyright 2007-2009 Selenium committers

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

     http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
 */

package org.openqa.selenium.internal.selenesedriver;

import com.thoughtworks.selenium.Selenium;
import com.thoughtworks.selenium.SeleniumException;

import org.openqa.selenium.NoSuchFrameException;
import org.openqa.selenium.WebDriverException;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Map;

public class SwitchToFrame implements SeleneseFunction<Void> {
  public Void apply(Selenium selenium, Map<String, ?> args) {
    Object id = args.get("id");

    if (id == null) {
      selenium.selectFrame("relative=top");
      return null;
    }

    try {
      if (id instanceof Number) {
        selenium.selectFrame("index=" + ((Number) id).longValue());
      } else if (id instanceof String) {
        selenium.selectFrame((String) id);
      } else if (id instanceof Map) {
        @SuppressWarnings({"unchecked"})
        String locator = getLocator((Map<String, ?>) id);
        selenium.selectFrame(locator);
      } else {
        throw new IllegalArgumentException("Illegal frame switch target: (" +
            id.getClass().getName() + ") " + id);
      }
    } catch (SeleniumException e) {
      throw new NoSuchFrameException(e.getMessage(), e);
    }

    return null;
  }

  private String getLocator(Map<String, ?> elementMap) {
    if (elementMap.containsKey("ELEMENT")) {
      try {
        return URLDecoder.decode((String) elementMap.get("ELEMENT"), "utf-8");
      } catch (UnsupportedEncodingException e) {
        // Should never happen.
        throw new WebDriverException(e);
      }
    }
    // Should never happen
    throw new IllegalArgumentException("Map does not define a WebElement");
  }
}
